﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SiteManager;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Configuration;

public partial class Community_AddBlog : System.Web.UI.Page
{
    Manager mgr = new Manager(true, "ConnectionString");
    protected void Page_Load(object sender, EventArgs e)
    {
        // txtDescription.RootPath = Session["strHttp"] + "includes/Editor/";
        BindCategory();
    }

    private void BindCategory()
    {
        //DataSet ds = CategoryDataSet();
        //if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
        //{
        //    ddlCategory.DataSource = ds;
        //    //ddlCategory.DataValueField = "Value";
        //    //ddlCategory.
        //    ddlCategory.DataBind();
        //}

        string strSql = !string.IsNullOrEmpty(ConfigurationManager.AppSettings["SelectCategoryQueryForBlog"])
            ? ConfigurationManager.AppSettings["SelectCategoryQueryForBlog"]
            : "SELECT Id as Value ,Name As Name FROM [dbhealthcare].[dbo].[tbl_PrimarySpeciality]";

        mgr.BindList(strSql, "Name", "Value", ddlCategory, "select");
    }

    private DataSet CategoryDataSet()
    {
        DataSet ds = new DataSet();
        string strSql = !string.IsNullOrEmpty(ConfigurationManager.AppSettings["SelectCategoryQueryForBlog"])
            ? ConfigurationManager.AppSettings["SelectCategoryQueryForBlog"]
            : "SELECT Id as Value ,Name As Name FROM [dbhealthcare].[dbo].[tbl_PrimarySpeciality]";


        return ds;
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(txtBlogTitle.Text))
        {

            lblMessage.Visible = true;
            lblMessage.Text = "Please enter Title";
            return;
        }
        //if (string.IsNullOrEmpty(txtDescription.EditorContent))
        if (string.IsNullOrEmpty(txtDescription.Text))
        {
            lblMessage.Visible = true;
            lblMessage.Text = "Please enter description";
            return;
        }
        Manager objManger = new Manager(true, "ConnectionString");
        int userType = 0;  //WILL USE TO SET ZERO(0) FOR DOCTOR AND 1 FOR DENTIST

        if (Session["userType"].ToString().Equals("Doctor", StringComparison.OrdinalIgnoreCase))
            userType = 2;
        //userType = 0; Change at 27/02/2008 because at pageresponse.aspx page  doctor usertype=2
        else if (Session["userType"].ToString().Equals("SiteUser", StringComparison.OrdinalIgnoreCase))
            userType = 3;
        else if (!string.IsNullOrEmpty(Session["userType"].ToString()) &&
            Session["userType"].ToString().Equals("Doctor", StringComparison.OrdinalIgnoreCase) &&
            !string.IsNullOrEmpty(Session["DoctorType"].ToString()) &&
            Session["DoctorType"].ToString().Equals("Dentist", StringComparison.OrdinalIgnoreCase))
            userType = 4;

        string strFileName = UploadFiles();

        //userType = 1; Change at 27/02/2008 because at pageresponse.aspx page  dentist usertype=4
        SqlParameter[] objSqlParameter = new SqlParameter[9];
        objSqlParameter[0] = new SqlParameter("@Id", SqlDbType.BigInt);
        //ADD BY RANJEET TO PASS BLOG ID AT 20/02/2008
        //objSqlParameter[0].Value = 0;
        if (btnSubmit.Text.ToUpper().Trim() == "Update".ToUpper().Trim())
        {
            objSqlParameter[0].Value = Convert.ToInt32(Session["EditID"].ToString());
        }
        else
        {
            objSqlParameter[0].Value = 0;
        }

        objSqlParameter[1] = new SqlParameter("@DoctorID", SqlDbType.BigInt);
        objSqlParameter[1].Value = Convert.ToInt32(Session["userID"]);
        objSqlParameter[2] = new SqlParameter("@DoctorType", SqlDbType.BigInt);
        objSqlParameter[2].Value = userType;
        objSqlParameter[3] = new SqlParameter("@BlogMessage", SqlDbType.Text);
        //objSqlParameter[3].Value = txtDescription.Text;
        objSqlParameter[3].Value = txtDescription.Text;//txtDescription.EditorContent;
        objSqlParameter[4] = new SqlParameter("@IsAddOrUpdate", SqlDbType.Bit);
        objSqlParameter[4].Direction = ParameterDirection.Output;
        objSqlParameter[5] = new SqlParameter("@BlogTitle", SqlDbType.Text);
        objSqlParameter[5].Value = txtBlogTitle.Text.ToString().Trim();

        objSqlParameter[6] = new SqlParameter("@BlogCategory", SqlDbType.BigInt);
        objSqlParameter[6].Value = !string.IsNullOrEmpty(ddlCategory.SelectedItem.Value) ? ddlCategory.SelectedItem.Value : "1";

        objSqlParameter[7] = new SqlParameter("@BlogPicture", SqlDbType.VarChar);
        objSqlParameter[7].Value = !string.IsNullOrEmpty(strFileName) ? strFileName : string.Empty;

        //ADDED AT 21/02/2008 TO INSERT BLOG POSTED DATE
        objSqlParameter[8] = new SqlParameter("@blogPostedDate", SqlDbType.DateTime);
        objSqlParameter[8].Value = System.DateTime.Now;

        objManger.ExecuteQuery("AddUpdateBlog", objSqlParameter);

        if (Convert.ToInt32(objSqlParameter[0].Value) == 0)
        {
            lblMessage.Visible = true; 
            lblMessage.ForeColor = System.Drawing.Color.Green;

            lblMessage.Text = "Blog Inserted successfully.";
            lblMessage.Font.Bold = true;
            clear_blockEditor();
        }
        else
        {
            lblMessage.Visible = true;
            lblMessage.Text = "Blog Updated Successfully.";
            lblMessage.Font.Bold = true;
            clear_blockEditor();
        }

        objManger = null;

        btnSubmit.Text = "Post";
        LoadBlog();
    }

    private string UploadFiles()
    {
        string filename1 = string.Empty;
        if (uploadPic.HasFile && uploadPic.PostedFile != null && uploadPic.PostedFile.FileName != "")
        {
            string ImgPath1 = "../BlogFiles/";
            filename1 = Path.GetFileName(uploadPic.PostedFile.FileName);
            string baseFile = Path.GetFileNameWithoutExtension(uploadPic.PostedFile.FileName);
            string extension = Path.GetExtension(uploadPic.PostedFile.FileName);
            int fileMatchCount = 1;
            // Check if a file with the given name exists in the Images1 subfolder of the root folder of your site
            while (File.Exists(Server.MapPath(Path.Combine(ImgPath1, filename1))))
            {
                filename1 = string.Format("{0}({1:D3}){2}", baseFile, fileMatchCount, extension);
                //  filename1 = string.Format("{0}({1:D2}){2}", baseFile, fileMatchCount + extension);
                fileMatchCount++;
            }
            uploadPic.SaveAs(Server.MapPath(Path.Combine(ImgPath1, filename1)));
        }
        return filename1;
    }

    public void LoadBlog()
    {
        Manager objManager = new Manager(true, "ConnectionString");
        SqlDataReader objDataReader = null;
        objDataReader = objManager.ExecuteQuery("select * from tbl_Blog where DoctorId=" + Convert.ToInt32(Session["userID"]));

        BindGrid(Convert.ToInt32(Session["userID"]));
        objManager = null;
    }

    private void BindGrid(int id)
    {
        //Filling the grid with the messages of the topic selected in the combo
        Manager mgrobj = new Manager(true, "ConnectionString");
        string sql = "select ID,Title from tbl_Blog where DoctorId=" + Convert.ToInt32(Session["userID"]) + "";
        DataSet ds = mgrobj.ExecuteQuery(sql, "tbl");
        if (ds.Tables[0].Rows.Count > 0)
        {
            grdMessages.DataSource = ds.Tables[0];
            //grdMessages.PageSize = Convert.ToInt32(Session["AdminPageSize"]);
            grdMessages.DataBind();
        }
        else // no topics exist
        {
            grdMessages.DataSource = ds.Tables[0];
            //grdMessages.PageSize = Convert.ToInt32(Session["AdminPageSize"]);
            grdMessages.DataBind();
            lblMessage.Text = "No Blog exist for you!!";
            lblMessage.ForeColor = System.Drawing.Color.Red;
            return;

        }
        mgrobj = null;
    }

    protected void grdMessages_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdMessages.PageIndex = e.NewPageIndex;
        BindGrid(Convert.ToInt32(Session["userID"]));
    }

    // delete confirmation
    protected void grdMessages_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        try
        {

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton lnk = (LinkButton)e.Row.FindControl("lnkDelete");

                try
                {
                    string id = grdMessages.DataKeys[e.Row.RowIndex].Value.ToString();
                    lnk.Attributes.Add("onclick", "return confirm('Are you sure to delete this blog?')");
                }
                catch (Exception es)
                {
                    Response.Write(es.ToString());
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }

    // delete the topic
    protected void grdMessages_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            string id = grdMessages.DataKeys[e.RowIndex].Value.ToString();
            string delSql = "delete from tbl_blog where doctorID=" + Convert.ToInt32(Session["userID"]) + " and id=" + id + "";
            mgr.ExecuteQuery(delSql);
            BindGrid(Convert.ToInt32(Session["userID"]));
            btnSubmit.Text = "Post";
            clear_blockEditor();
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }

    protected void grdMessages_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.ToString().ToUpper().Trim() == "Editblog".ToUpper().Trim())
        {

            Manager objManager = new Manager(true, "ConnectionString");
            SqlDataReader objDataReader = null;
            //string editSql = "update blog set BlogMessage='nnnnnnnn', BlogTitle='mmmmmm' where doctorID=759462 and id=6";
            string id = e.CommandArgument.ToString();
            Session["EditID"] = id;
            string editsql = "select * from tbl_Blog where doctorID=" + Convert.ToInt32(Session["userID"]) + " and id=" + id + "";
            objDataReader = objManager.ExecuteQuery(editsql);
            objDataReader.Read();
            if (objDataReader.HasRows)
            {
                txtDescription.Text = objDataReader["description"].ToString();
                //  txtDescription.EditorContent = objDataReader["description"].ToString();
                txtBlogTitle.Text = objDataReader["Title"].ToString();
                //SET VISIBILITY
                //BlogMainTable.Visible = true;
                //BlogGridTable.Visible = false;
                lblMessage.Text = "";
                btnSubmit.Enabled = true;
                btnSubmit.Text = "Update";
            }
            objDataReader.Close();
            objManager = null;
        }
    }

    protected void lnkNewEntry_Click(object sender, EventArgs e)
    {
        btnSubmit.Text = "Post";
        clear_blockEditor();
    }
    protected void clear_blockEditor()
    {
        //txtDescription.EditorContent = string.Empty;
        txtDescription.Text = string.Empty;
        txtBlogTitle.Text = string.Empty;
    }
}